<?php

namespace app\admin\controller;

use think\Db;
use app\enumerations\CustomerCurrentLevelEnum;
use app\enumerations\CustomerStatusEnum;

class Customer extends Common {

    /**
     * 客户列表
     * @return mixed
     */
    public function index(){

        $condition = $this->convertRequestToWhereSql();

        $list = $this->customerService->getCustomerList($condition);

        $this->assign('list',$list);

        return $this->fetch();

    }

    /**
     * sql转换
     * @return mixed
     */
    public function convertRequestToWhereSql() {

        $whereSql = " 1=1";
        $pageMap = [];

        $params = input("param.");

        foreach($params as $key => $value) {

            if($value == "-999"
                || isNullOrEmpty($value))
                continue;

            switch ($key) {

                case "id":
                    $whereSql .= " and id = '".$value."'";
                    break;
                case "nickname":
                    $whereSql .= " and nickname LIKE '%".$value."%'";
                    break;
                case "yx_pid":
                    $whereSql .= " and yx_pid = '".$value."'";
                    break;
                case "current_level":
                    $whereSql .= " and current_level = '".$value."'";
                    break;
            }

            $pageMap[$key] = $value;
            $this->assign($key, $value);

        }

        $data["whereSql"] = $whereSql;
        $data["pageMap"] = $pageMap;

        return $data;

    }

    /**
     * 用户详情
     * @return mixed
     */
    public function edit() {

        $id = input('param.id');

        $customer = $this->customerService->findById($id);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        // 上级用户
        $parentCustomer = '';
        if ($customer['parent_customer_id'] != 0) {

            $parentCustomer = $this->customerService
                ->findById($customer['parent_customer_id']);
        }

        // 下级用户人数
        $childCustomerNumber = $this->customerService
            ->getChildCustomerCountByCustomerId($customer['id']);

        $this->assign('customer', $customer);
        $this->assign('parentCustomer', $parentCustomer);
        $this->assign('childCustomerNumber', $childCustomerNumber);
        return $this->fetch();

    }

    /**
     * 检查是否满足变更等级条件
     */
    public function checkCurrentLevel() {

        $post = $this->request->post();

        $customer = $this->customerService->findById($post['customer_id']);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        if (!checkEnumValue($post['current_level'],
            CustomerCurrentLevelEnum::getAllList())) {
            $this->error('权限非法数据');
        }

        // 如果更换了等级
        if ($customer['current_level'] != $post['current_level']) {

            // 如果目标等级 大于当前等级 则判断等级规则
            if ($post['current_level'] > $customer['current_level']) {

                // 查找等级规则
                $level = $this->levelService->findByLevel($post['current_level']);

                if (isNullOrEmpty($level)) {
                    $this->error('等级规则不存在');
                }

                $result = $this->customerService
                    ->checkChangeLevelCondition($customer, $level);

                if (!$result['success']) {

                    if ($result['code'] == 1) {
                        $this->error('不满足(我-最小收益)修改条件，确认变更吗？','', 'confirm');
                    }

                    if ($result['code'] == 2) {
                        $this->error('不满足(我下级-最小收益总和)修改条件，确认变更吗？', '', 'confirm');
                    }

                    if ($result['code'] == 3) {
                        $this->error('不满足(团队内超级店长数量)修改条件，确认变更吗？', '', 'confirm');
                    }

                    if ($result['code'] == 4) {
                        $this->error('不满足(非直属有效店长(及以上级别)总数)修改条件，确认变更吗？', '', 'confirm');
                    }

                    if ($result['code'] == 5) {
                        $this->error('不满足(非直属店长(及以上级别)总数)修改条件，确认变更吗？', '', 'confirm');
                    }

                    if ($result['code'] == 6) {
                        $this->error('不满足(直属有效店长(及以上级别)总数)修改条件，确认变更吗？', '', 'confirm');
                    }

                    if ($result['code'] == 7) {
                        $this->error('不满足(直属店长(及以上级别)总数)修改条件，确认变更吗？', '', 'confirm');
                    }
                }
            }
        }

        $this->success('满足修改条件，是否继续变更？');

    }

    /**
     * 变更等级
     */
    public function changeCurrentLevel() {

        $post = $this->request->post();

        $customer = $this->customerService->findById($post['customer_id']);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        if (!checkEnumValue($post['current_level'],
            CustomerCurrentLevelEnum::getAllList())) {
            $this->error('权限非法数据');
        }

        $customerData['current_level'] = $post['current_level'];

        Db::startTrans();
        try {

            $this->customerService->updateByIdAndData($customer['id'], $customerData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            $this->error('服务器错误,请稍后再试');

        }

        $this->success('变更成功');

    }

    /**
     * 上级详情
     * @return mixed
     */
    public function parentCustomerInfo() {

        $customerId = $this->request->param('customer_id');

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        $parentCustomer = $this->customerService
            ->findById($customer['parent_customer_id']);

        if (isNullOrEmpty($parentCustomer)) {
            $this->error('暂无上级');
        }

        $this->assign('customer', $customer);
        $this->assign('parentCustomer', $parentCustomer);
        return $this->fetch();

    }

    /**
     * 解除上级关系
     */
    public function relieveParentCustomer() {

        $customerId = $this->request->param('customer_id');

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        $customerData['parent_customer_id'] = 0;

        Db::startTrans();
        try {

            $this->customerService->updateByIdAndData($customerId, $customerData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            $this->error('服务器错误,请稍后再试');

        }

        $this->success('解除成功');

    }

    /**
     * 下级列表
     * @return mixed
     */
    public function childCustomerList() {

        $customerId = $this->request->param('customer_id');

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        $requestMap = $this->convertRequestToMap();

        unset($requestMap['condition']['customer_id']);
        unset($requestMap['page']['customer_id']);

        $requestMap['condition']['parent_customer_id'] = $customerId;
        $requestMap['page']['parent_customer_id'] = $customerId;

        $list = $this->customerService->getCustomerListByRequestMap($requestMap);

        $this->assign('list', $list);
        $this->assign('customer', $customer);
        return $this->fetch();

    }

    /**
     * 历史订单列表
     * @return mixed
     */
    public function historyOrderList() {

        $customerId = $this->request->param('customer_id');

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        $condition = $this->convertRequestToWhereSqlForHistoryOrderList($customer['id']);

        $list = $this->orderService->getHistoryOrderList($condition);

        $this->assign('list', $list);
        $this->assign('customer', $customer);
        return $this->fetch();

    }

    /**
     * sql转换
     * @return mixed
     */
    public function convertRequestToWhereSqlForHistoryOrderList($customerId) {

        $whereSql = " 1=1";
        $pageMap = [];

        $params = input("param.");

        foreach($params as $key => $value) {

            if($value == "-999"
                || isNullOrEmpty($value))
                continue;

            switch ($key) {

                case "orderPayTime":
                    $dateArr = explode(' - ', $params['orderPayTime']);
                    $whereSql .= " and order_pay_time >= '".$dateArr[0]." 00:00:00' and order_pay_time <= '".$dateArr[1]." 23:59:59'";
                    break;
                case "id":
                    $whereSql .= " and id LIKE '%".$value."%'";
                    break;
                case "yx_pid":
                    $whereSql .= " and yx_pid LIKE '%".$value."%'";
                    break;
                case "nickname":
                    $whereSql .= " and nickname LIKE '%".$value."%'";
                    break;
                case "order_sn":
                    $whereSql .= " and order_sn LIKE '%".$value."%'";
                    break;
                case "goods_name":
                    $whereSql .= " and goods_name LIKE '%".$value."%'";
                    break;
                case "order_status":
                    $whereSql .= " and order_status = '".$value."'";
                    break;
                default:
                    $whereSql .= " and (first_customer_id = '".$customerId."' 
                                || second_customer_id = '".$customerId."' 
                                || third_customer_id = '".$customerId."')";
                    break;
            }

            $pageMap[$key] = $value;
            $this->assign($key, $value);

        }

        $data["whereSql"] = $whereSql;
        $data["pageMap"] = $pageMap;

        return $data;

    }

    /**
     * 收益
     * @return mixed
     */
    public function profit() {

        $customerId = $this->request->param('customer_id');

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        // 获取未结算金额
        $waitingSettleNumber = $this->customerService
            ->getWaitingSettleNumber($customer['id']);

        $waitingSettleNumber = $waitingSettleNumber[0]['waiting_settle_number'];
        if (isNullOrEmpty($waitingSettleNumber)) {
            $waitingSettleNumber = 0;
        }

        $this->assign('customer', $customer);
        $this->assign('waitingSettleNumber', $waitingSettleNumber);
        return $this->fetch();

    }

    /**
     * 修改用户收益状态
     */
    public function changeCustomerStatus() {

        $customerId = $this->request->param('customer_id');
        $customerStatus = $this->request->param('customer_status');

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            $this->error('用户不存在');
        }

        if (!checkEnumValue($customerStatus, CustomerStatusEnum::getAllList())) {
            $this->error('收益状态数据非法');
        }

        Db::startTrans();
        try {

            $customerData['status'] = $customerStatus;
            $this->customerService->updateByIdAndData($customerId, $customerData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            $this->error('服务器错误,请稍后再试');

        }

        $this->success('修改成功');

    }

}